const express = require("express");
const { createServer } = require("node:http");
const { join } = require("node:path");
const app = express();
const server = createServer(app);
const { Server } = require("socket.io"); //socket.io
var router = express.Router();
var { loginmodel, shouModel, yueModel } = require('../model/model')

const jwt = require('jsonwebtoken')
const secretKey = 'k';
const bcrypt = require('bcrypt')
const SMSClient = require('@alicloud/sms-sdk'); //导入模块

// 刷新token
router.post('/refresh', (req, res) => {
  const { refreshToken } = req.body;
  if (refreshToken == null) return res.sendStatus(401);
  jwt.verify(refreshToken, secretKey, (err, user) => {
    if (err) return res.sendStatus(403);
    const accessToken = jwt.sign({ phonenum: user.phonenum, password: user.password }, secretKey, { expiresIn: 60 * 15 });
    res.send({ accessToken });
  });
});

router.post('/login', async (req, res) => {
  let { phonenum, password } = req.body
  console.log(req.body)
  let data = await loginmodel.findOne({ phonenum })
  if (data != null) {
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(password, salt, (err, hash) => {
        password = hash
        // console.log(hash)
      })
    })
    bcrypt.compare(password, data.password, (err, result) => {
      if (result) {
        const accessToken = jwt.sign({ phonenum, password }, secretKey, { expiresIn: 60 * 15 });
        const refreshToken = jwt.sign({ phonenum, password }, secretKey, { expiresIn: '7d' });
        res.send({
          code: 200,
          data,
          token: { accessToken, refreshToken },
          msg: '登录成功'
        })
      } else {
        res.send({
          code: 404,
          msg: '账号或密码错误'
        })
      }
    })
  } else {
    res.send({
      code: 404,
      msg: '账号或密码错误'
    })
  }
})

router.post('/register', async (req, res) => {
  let { phonenum, password } = req.body
  console.log(req.body, '注册')
  bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(password, salt, (err, hash) => {
      password = hash
      // console.log(hash)
    })
  })
  let a = await loginmodel.find({ phonenum })
  if (a.length === 0) {
    await loginmodel.create({ phonenum, password })
    res.send({
      code: 200,
      msg: '注册成功'
    })
  } else {
    res.send({
      code: 409,
      msg: '手机号已存在'
    })
  }
})

router.post('/editpassword', async (req, res) => {
  let { phonenum, password } = req.body
  let a = await loginmodel.find({ phonenum })
  console.log(a)
  if (a.length !== 0) {
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(password, salt, async (err, hash) => {
        // password = hash
        console.log(hash, "hash hash hash")
        await loginmodel.updateOne({ phonenum }, { password: hash })
      })
    })
    console.log(password, "password")
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } else {
    res.send({
      code: 404,
      msg: '手机号不存在'
    })
  }
})

router.post('/edittel', async (req, res) => {
  let {tel, newtel} = req.body
  await loginmodel.updateOne({phonenum: tel}, {phonenum: newtel})
  res.send({
    code: 200,
    msg: "换绑成功"
  })
})

/* GET home page. */
router.get('/shou', async (req, res) => {
  let { name, zhi } = req.query
  let shou = await shouModel.find()
  if (name) {
    shou = shou.filter(i => i.name.includes(name))
  }
  if (zhi) {
    shou = shou.filter(i => i.zhi.includes(zhi))
  }
  res.send({
    shou
  })
});

router.get('/yue', async (req, res) => {
  let yue = await yueModel.find()
  res.send({
    yue
  })
})
router.post('/add', async (req, res) => {
  await yueModel.create(req.body)
  console.log()
  res.send({
    code: 200,
    msg: '预约成功'
  })
})

// 初始化sms_client
let smsClient = new SMSClient({
  accessKeyId: "LTAI5tFRZ8n7aybpYZWM7Wd3", // 阿里云 AccessKey ID
  secretAccessKey: "8RgNcSAZBYwSO4NhmXUD4X8ihCOzBh" // 阿里云 AccessKey Secret
});

// 验证码生成
function generateCode() {
  let code = "";
  for (let i = 0; i < 6; i++) {
    code = code + Math.floor(Math.random() * 10); // 随机生成 6 位数字验证码
  }
  return code;
}

router.post('/getCode', function (req, res, next) {
  let phonenum = req.body.phonenum; // 从前端获取到手机号码

  // 验证手机号是否为空
  if (!phonenum || phonenum.trim() === "") {
    return res.status(400).send("Phone number is required."); // 使用 res.send() 返回错误消息
  }

  // 生成验证码
  let code = generateCode();
  console.log("Generated code:", code);
  res.send({
    code: 200,
    codes: code
  })
  return

  // 发送短信
  smsClient.sendSMS({
    PhoneNumbers: phonenum, // 必填: 待发送手机号
    SignName: '萱0226', // 必填: 短信签名
    TemplateCode: 'SMS_478870489', // 必填: 短信模板
    TemplateParam: `{\"code\":\"${code}\"}` // 必填: 模板中的变量替换
  }).then(function (response) {
    let { Code } = response; // 获取返回的状态码
    if (Code === 'OK') {
      // 短信发送成功
      console.log("SMS sent successfully:", response);
      return res.send({ code: 200, msg: 'SMS sent successfully.', codes: code }); // 使用 res.send() 返回成功信息和验证码
    } else {
      // 短信发送失败
      console.log("Error sending SMS:", response);
      return res.status(500).send("Failed to send SMS."); // 使用 res.send() 返回错误信息
    }
  }).catch(function (err) {
    // 捕获发送短信的错误
    console.log("Error:", err);
    return res.status(500).send("Error sending SMS."); // 使用 res.send() 返回错误信息
  });
});

router.get('/shou', async (req, res) => {
  let { name, zhi } = req.query
  let shou = await shouModel.find()

  if (name) {
    shou = shou.filter(i => i.name.includes(name))
  }
  if (zhi) {
    shou = shou.filter(i => i.zhi.includes(zhi))
  }
  res.send({
    shou
  })
});


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/getA', async (req, res) => {
  res.send({ code: 200, msg: '获取成功' })
})

router.post('/getB', async (req, res) => {
  await console.log(req.body);
  res.send({ code: 200, msg: '发送成功' })
})



const path = require('path')
app.use('/uploads', express.static(path.join(__dirname, '/uploads')));
app.use('/audioUploads', express.static(path.join(__dirname, 'audioUploads')));
// 引入 fs 模块
const fs = require('fs');
const multer = require('multer');



const io = new Server(server, { cors: true });



app.get("/", (req, res) => {
  res.send("<h1>Hello world</h1>");
});

app.get("/", (req, res) => {
  res.sendFile(join(__dirname, "index.html"));
});

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = join(__dirname, 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdir(uploadDir, { recursive: true }, (err) => {
        if (err) {
          return cb(err);
        }
        cb(null, uploadDir);
      });
    } else {
      cb(null, uploadDir);
    }
  },
  filename: (req, file, cb) => {
    const buf = Buffer.from(file.originalname, 'latin1');
    const fileName = buf.toString('utf-8');
    cb(null, Date.now() + '-' + fileName);
  },
});

const storageAudio = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = join(__dirname, 'audioUploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdir(uploadDir, { recursive: true }, (err) => {
        if (err) {
          return cb(err);
        }
        cb(null, uploadDir);
      });
    } else {
      cb(null, uploadDir);
    }
  },
  filename: (req, file, cb) => {
    // 尝试从blob对象获取格式信息或设置默认格式
    const fileName = Date.now() + '.wav';
    cb(null, fileName);
  },
});
const uploadAudio = multer({ storage: storageAudio });

app.post('/uploadAudio', uploadAudio.single('audio'), (req, res) => {
  const audioPath = req.file.path;
  // 从请求中获取用户信息
  const sender = req.body.username;
  io.emit('audioMessage', { path: audioPath, username: sender });
  res.send('音频上传成功');
});

const upload = multer({ storage });

app.post('/upload', upload.single('image'), (req, res) => {
  const imagePath = req.file.path;
  // 从请求中获取用户信息
  const sender = req.body.username;
  io.emit('imageMessage', { path: imagePath, isUploaded: true, username: sender });
  res.send('图片上传成功');
});

io.on('connection', (socket) => {
      // 接收客户端的心跳包
      socket.on('heartbeat', (data) => {
        console.log('Received heartbeat:', data);
        // 发送心跳响应
        socket.emit('heartbeat', 'pong');
    });

    // 接收客户端的消息
    socket.on('message', (newMessage, user) => {
        console.log(newMessage, user);
        // 确保只广播一次消息
        io.emit('message', newMessage.message, user);
        // 发送确认消息
        socket.emit('messageAck', newMessage.id);
    });

  socket.on('imageMessage', async (imageData, user) => {
    const base64Data = imageData.replace(/^data:image\/\w+;base64,/, '');
    const buffer = Buffer.from(base64Data, 'base64');
    const uploadDir = join(__dirname, 'uploads');
    try {
      await fs.access(uploadDir);
    } catch (error) {
      await fs.mkdir(uploadDir, { recursive: true });
    }
    const imageName = Date.now() + '-' + encodeURIComponent(imageData.match(/filename="([^"]+)"/)[1]);
    const imagePath = join(uploadDir, imageName);
    // const imagePath = join(uploadDir, `${Date.now()}.png`);
    try {
      await fs.writeFile(imagePath, buffer);
      io.emit('imageMessage', { path: imagePath, isUploaded: false });
    } catch (error) {
      console.error('保存图片时出现错误：', error);
    }
  });
  socket.on('videoMessage', async (video, user) => {
    console.log(video, user);
    io.emit('videoMessage', video, user);
  });
});

const OpenAI = require('openai');

router.post('/getChat', async (req, res) => {
  const openai = new OpenAI({
    // 配置自己的key
    apiKey: 'a5e7b031-ecb0-496d-8fb4-0caa88d934c8',
    baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
  });
  try {
    const stream = await openai.chat.completions.create({
        messages: [
            { role: 'system', content: '你是在线资讯（客服），请用中文回答用户的问题' },
            { role: 'user', content: req.body.content },
        ],
        model: 'ep-20241107134422-lx86j',
        stream: true,
    });

    // 设置响应头为事件流
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    for await (const part of stream) {
        const content = part.choices[0]?.delta?.content || '';
        if (content) {
            // 发送每个数据块到前端
            res.write(`data: ${JSON.stringify({ content })}\n\n`);
        }
    }

    // 结束响应
    res.end();
  } catch (error) {
    console.error('Error in OpenAI request:', error);
    res.status(500).send({
        code: 500,
        msg: '获取文章失败',
        data: null
    });
  }
});

server.listen(3001, () => {
  console.log("server running at http://localhost:3001");
});
module.exports = router;


